package com.tsite.service.common;

import java.io.ByteArrayOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.tsite.common.report.ReportEngine;
import com.tsite.common.report.ReportRequest;
import com.tsite.common.report.ReportType;

@Service
public class ReportDownloader {
	
	public static final String MEDIA_TYPE_EXCEL = "application/vnd.ms-excel";
	public static final String MEDIA_TYPE_PDF = "application/pdf";
	public <T> void download(ReportRequest<T> reportRequest, HttpServletResponse response)
	{				
		ReportEngine reportEngine = ReportEngine.getInstance();
		ByteArrayOutputStream baos;
		try {
			baos = reportEngine.generate(reportRequest);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		if (reportRequest.getReportType().equals(ReportType.XLS)) {
			 
			// Set our response properties
			// Here you can declare a custom filename
			String fileName = reportRequest.getGeneratedName() + reportRequest.getReportType().getValue();
			response.setHeader("Content-Disposition", "inline; filename=" + fileName);
			
			// Set content type
			response.setContentType(MEDIA_TYPE_EXCEL);
			response.setContentLength(baos.size());
		}
		
		if (reportRequest.getReportType().equals(ReportType.PDF)) {
			 
			// Set our response properties
			// Here you can declare a custom filename
			String fileName = reportRequest.getGeneratedName() + reportRequest.getReportType().getValue();
			response.setHeader("Content-Disposition", "inline; filename="+ fileName);
			
			// Set content type
			response.setContentType(MEDIA_TYPE_PDF);
			response.setContentLength(baos.size());
							
		} 	

		write(response, baos);
					
	}
	
	/**
	* Writes the report to the output stream
	*/
	private void write(HttpServletResponse response,
			ByteArrayOutputStream baos) {
		 
		try {
//			logger.debug(baos.size());
			
			// Retrieve output stream
			ServletOutputStream outputStream = response.getOutputStream();
			// Write to output stream
			baos.writeTo(outputStream);
			// Flush the stream
			outputStream.flush();
			
			// Remove download token
//			tokenService.remove(token);
			
		} catch (Exception e) {
//			logger.error("Unable to write report to the output stream");
			throw new RuntimeException(e);
		}
	}	
}
